
#example controller for Graaasp.
class GraaaspController < SessionsController
  include AuthenticatedSystem
  before_filter :test_data, lambda { |c| Rails.env == 'development' }
  unloadable
  
  # Login action. Handle posts from the login screen by doing a redirect
  # if no uri is provided redirect to the secured uri /shibboleth/login
  def login_direct
    uri = params[:login_uri]
    unless uri.empty?
      redirect_to uri
    else
      redirect_to '/shibboleth/login'
    end
  end

  #Login action. The route pointing to this action should be protected
  #by a Shibboleth directive
  def login
    to = request.env[:HTTP_REFERER]
    to = to.blank? ? '/' : to

    if application_loggedin?
      redirect_to to
      return
    end

    Shibboleth::authenticate(request) do |user|
      application_login user
    end
    redirect_to to
  end
  
  protected
  
  def application_loggedin?
    current_user.not_guest? && logged_in?
  end

  def application_login(user)
    if application_loggedin?
      return false
    end

    unless user
      return false
    end

    u = ensure_user user


    @center_id= session[:return_id] # copy session to return to center item
    @center_type= session[:return_type]
    common_destroy(false) # remove the default guest_user session
    
    self.current_user = u
    common_login
    load_center
    session[:email]= u.email
  end

  def ensure_user user
    # VALIDITY & UNIQUENESS OF EMAIL CHECKED IN CONTROLLER
    u = User.find(:first, :conditions   => ['email= ?', user['email']])
    if u.nil? # user doesn't exist
      u = User.new
      u.email = user['email']
      u.name = user['email'].gsub(/@.*/,"")
      u.first_name = user['firstname']
      u.last_name = user['lastname']
      u.organization = user['organization']
      u.automatically_created = false
      require 'digest'
      u.password = Digest::MD5.hexdigest rand(1000000000).to_s + Time.now.to_s
      u.password_confirmation = u.password
      u.save
      u.activate
    else
      u.email = user['email']
      u.name = user['email'].gsub(/@.*/,"")
      u.first_name = user['firstname']
      u.last_name = user['lastname']
      u.organization = user['organization']
      u.save
    end
    return u
  end

  private

  #add test data to simulate remote user's data
  def test_data
    unless Rails.env == 'development'
      return false
    end
    require Shibboleth.root('test', 'aai.rb')
    Shibboleth::Test::Aai.user request
  end
end
